import { useNavigate, useLocation, useBeforeLeave } from '@solidjs/router';

export const useTitleBarStore = () => {
  const navigate = useNavigate();
  const location = useLocation();
  let lastScrollPosition = 0;

  // 定义可返回的路由前缀列表
  const BACK_ROUTE_PREFIXES = ['/app', '/search', '/collectionDetail'] as const;
  
  const canGoBack = () => {
    return BACK_ROUTE_PREFIXES.some(prefix => location.pathname.startsWith(prefix));
  };

  const saveScrollPosition = () => {
    const mainContent = document.getElementById('main-content');
    if (mainContent) {
      lastScrollPosition = mainContent.scrollTop;
    }
  };

  const restoreScrollPosition = () => {
    if (lastScrollPosition) {
      const mainContent = document.getElementById('main-content');
      if (mainContent) {
        mainContent.scrollTop = lastScrollPosition;
        lastScrollPosition = 0;
      }
    }
  };

  const goBack = () => {
    navigate(-1);
    // 增加延迟时间以确保页面完全加载
    setTimeout(restoreScrollPosition, 50);
  };

  const refresh = (onRefresh?: () => void) => {
    if (onRefresh) {
      onRefresh();
    }
  };

  // 使用useBeforeLeave在路由离开前保存滚动位置
  useBeforeLeave((_e) => {
      if(!location.pathname.startsWith('/app'))
      {
        saveScrollPosition();
      }
  });

  return {
    canGoBack,
    goBack,
    refresh
  };
};